package com.example.itcacp.repository.mybatis;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.itcacp.entity.Content;
import com.example.itcacp.entity.Message;
import com.example.itcacp.entity.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Set;

public interface MessageMapper extends BaseMapper<Message> {

    /**
     * 未读数量统计
     * */
    @Select ( "SELECT COUNT(*) FROM itcacp.me_message WHERE " +
            "receiver_id = #{receiverId} AND target_type = #{contentType} AND status = #{status}" )
    int countByReceiverIdAndStatusAndMessageType(Long receiverId, String status, Message.MessageType messageType);


    /**
     * 根据消息类型查询公告列表（假设公告类型为 MessageType.NOTICE）
     */
    @SelectProvider(type = messageSqlProvider.class, method = "selectMessageAll")
    List<Message> findByMessageTypeAndContent(Message.MessageType messageType,String content);


    class messageSqlProvider {
        public String selectMessageAll(Message.MessageType messageType, String content) {
            return new SQL () {{
                SELECT("*");
                FROM("me_message");
                boolean hasWhere = false;  // 记录是否已经存在where子句
                if (messageType != null) {
                    WHERE("message_type = #{messageType}"); // like模糊查询
                    hasWhere = true;  // 存在则需要添加and子句
                }
                if (content != null && !content.isEmpty()) {
                    if (hasWhere) {
                        AND();
                    }
                    WHERE("content LIKE CONCAT('%', #{content}, '%')");
                }
                ORDER_BY("created_at DESC");  //倒序排序
            }}.toString();
        }
    }


    /**
     * 查询对应接收者的全部内容
     * */
    @Select("SELECT * FROM me_message " +
            "WHERE receiver_id = #{receiverId} " +
            "AND message_type = #{messageType} " +
            "ORDER BY created_at DESC")
    @Results({
            @Result(property = "messageId", column = "message_id"),
            @Result(property = "senderId", column = "sender_id"),
            @Result(property = "receiverId", column = "receiver_id"),
            @Result(property = "messageType", column = "message_type"),
            @Result(property = "targetId", column = "target_id"),
            @Result(property = "targetType", column = "target_type"),
            @Result(property = "title", column = "title"),
            @Result(property = "content", column = "content"),
            @Result(property = "status", column = "status"),
            @Result(property = "createdAt", column = "created_at"),
            @Result(property = "targetContent", column = "target_id", javaType = Content.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.ContentMapper.findContentById")),
            @Result(property = "sender", column = "sender_id", javaType = User.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.UserMapper.findBolgUserById")),
    })
    List<Message> getMessagesByReceiverIdAndMessageType(
            @Param("receiverId") Long receiverId,
            @Param("messageType") Message.MessageType messageType);





    /**
     * 聊天记录查询
     * */
    @Select("SELECT * FROM me_message " +
            "WHERE ((sender_id = #{senderId} AND receiver_id = #{receiverId}) " +
            "OR (sender_id = #{receiverId} AND receiver_id = #{senderId})) AND message_type = #{messageType} ORDER BY created_at ASC")
    @Results({
            @Result(property = "messageId", column = "message_id"),
            @Result(property = "senderId", column = "sender_id"),
            @Result(property = "receiverId", column = "receiver_id"),
            @Result(property = "messageType", column = "message_type"),
            @Result(property = "title", column = "title"),
            @Result(property = "content", column = "content"),
            @Result(property = "status", column = "status"),
            @Result(property = "createdAt", column = "created_at"),
            @Result(property = "sender", column = "sender_id", javaType = User.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.UserMapper.findBolgUserById")),
            @Result(property = "receiver", column = "receiver_id", javaType = User.class,
                    one = @One(select = "com.example.itcacp.repository.mybatis.UserMapper.findBolgUserById")),
    })
    List<Message> getChatMessages(Long senderId, Long receiverId, Message.MessageType messageType);

    /**
     * 获取与指定用户有消息往来的所有联系人详情
     * @param userId 当前用户ID
     * @return 联系人详情列表（去重）
     */
    @Select("SELECT u.* FROM it_user u " +
            "WHERE u.user_id IN (" +
            "  SELECT DISTINCT user_id FROM (" +
            "    SELECT sender_id AS user_id FROM me_message WHERE receiver_id = #{userId} " +
            "    UNION ALL " +
            "    SELECT receiver_id AS user_id FROM me_message WHERE sender_id = #{userId} " +
            "  ) AS temp " +
            "  WHERE user_id != #{userId}" +
            ")")
    @Results({
            @Result(property = "user_id", column = "user_id"),
            @Result(property = "username", column = "username"),
            @Result(property = "profile_photo_path", column = "profile_photo_path")
    })
    List<User> selectContactUsers(@Param("userId") Long userId);

}
